import { request } from "../../utils/util";
let app = getApp()

Page({
  data: {
    selectId: 0,
    pay_money: '',
    list: []
  },
  // 获取列表数据
  getList(page) {
    request({
      url: '/api/web/personal/recharge-setting',
      params: {
        page
      },
      success: ({ code, data }) => {
        if (code === 200) {
          if (data.length) {
            this.data.selectId = data[0].id
            this.data.pay_money = data[0].recharge
          }
          this.setData({
            list: data,
            selectId: this.data.selectId
          })
        }
      }
    })
  },
  select (e) {
    let { item } = e.currentTarget.dataset
    this.setData({
      selectId: item.id,
      pay_money: item.recharge
    })
  },
  // 充值
  recharge() {
    request({
      url: '/api/web/personal/recharge',
      method: 'POST',
      data: {
        recharge_id: this.data.selectId
      },
      success: ({ code, data, message }) => {
        if (code === 200) {
          this.wxPay(data.order_sn)
        } else {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 微信支付
  wxPay(order_sn) {
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url: '/api/web/wechat',
      method: 'POST',
      data: {
        openid: app.globalData.userInfo.openid,
        type: 'recharge',
        order_sn,
        pay_money: this.data.pay_money,
      },
      success: ({ code, data, message }) => {
        wx.hideLoading()
        if (code === 200) {
          wx.requestPayment({
            timeStamp: `${data.timeStamp}`,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success: (result) => {
              if (result.errMsg === 'requestPayment:ok') {
                wx.showToast({
                  title: '充值成功！',
                  icon: 'success',
                  duration: 2000
                })
                setTimeout(() => {
                  wx.navigateBack()
                }, 1000)
              } else {
                wx.showToast({
                  title: result.errMsg,
                  icon: 'none',
                  duration: 2000
                })
              }
            },
            fail (err) {
              console.log(err)
            }
          })
        } else {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  onShow () {
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#000000',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
    this.getList()
  }
})
